/*
 * sys_mng.c
 *
 *  Created on: 2023年10月12日
 *      Author: hm
 */
#include "sys_mng.h"
#include "string.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "freertos/queue.h"
#include "driver/uart.h"
#include "mqtt_client.h"
#include "../inc/aht20.h"
#include "../inc/mqtt.h"

static const char* TAG = "sys_mng";
QueueHandle_t Queue_matt_msg;

void task_Message_Send(SYSTEM_MNG_EVENT_MSG Message)
{
    xQueueSend(Queue_matt_msg, &Message, 0);
}

void task_Message_SendFromISR(SYSTEM_MNG_EVENT_MSG Message)
{
    xQueueSendFromISR(Queue_matt_msg, &Message, 0);
}

static TaskHandle_t task_mqtt_thread;
static TaskHandle_t task_iic_thread;

void task_mqtt_handler(void * arg)
{
	SYSTEM_MNG_EVENT_MSG EventMsg = {0};
    Queue_matt_msg = xQueueCreate(10, sizeof(SYSTEM_MNG_EVENT_MSG));
    while (1)
    {
        if (pdPASS == xQueueReceive(Queue_matt_msg, &EventMsg, 100/portTICK_PERIOD_MS))
        {

            switch (EventMsg.u8Event)
            {
                case MSG_MQTT_PUBLISH:
                {
                	char buf[30];
                	sprintf(buf, "temp=%3.2f  humidity=%3.2f",g_aht20_data.temperature,g_aht20_data.rel_humidity);
                	esp_mqtt_client_publish(my_mqtt_client, user_update,buf,strlen(buf),0,false);

                	break;
                }
                case MSG_IIC_DATA_COLLECTION:
                {

                	break;
                }

            }
        }
    }
}

void Tasks_init(void)
{
	/*数值越高，任务优先级越高*/
    xTaskCreate(task_mqtt_handler, "task_mqtt_handler", 2*1024, NULL, 1, task_mqtt_thread);

    xTaskCreate(aht20_read_measures, "task_iic_thread", 2*1024, NULL, 1, task_iic_thread);
	//Start FreeRTOS scheduler.
	//vTaskStartScheduler();
}

static TimerHandle_t timer_100ms; //10hz timer

#define TIMER_PERIOD_100MS      pdMS_TO_TICKS(100)

void timer_100ms_handle(TimerHandle_t xTimer )
{
	static SYSTEM_MNG_EVENT_MSG t_msg = {0};
	static uint32_t timer_cnt = 0;
	timer_cnt++;
	if(0 == timer_cnt % 10)
	{
		t_msg.u8Event = MSG_MQTT_PUBLISH;
		task_Message_Send(t_msg);
	}
}

void Timers_init(void)
{
	timer_100ms = xTimerCreate("TIMER_10HZ", TIMER_PERIOD_100MS, pdTRUE, NULL, timer_100ms_handle);

	xTimerStart(timer_100ms, 0);
}

